package com.itchu.auth.config;

import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class OnlineCounter {

    // 声明一个map,键存用户的key，value存过期时间，使用ConcurrentHashMap是因为它是线程安全的
    private static Map<String,Object> map = new ConcurrentHashMap<>();

    // 初始化map集合
    public void initMap(String key, Date expTime) {
        map.put(key,expTime);
    }

    // 获取在线用户数
    public Integer getOnlineCounter() {
        Integer counter = 0;
        Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Date expTime = (Date) iterator.next().getValue();
            if (expTime.getTime() > System.currentTimeMillis()) {
                counter++;
            }
        }
        return counter;
    }

    /*
     * 获取txt文件中的数字，即之前的访问量
     * 传入参数为： 字符串: txtFilePath,文件的绝对路径
     */

    public Long getTotalVisit() {

        try {
            //读取文件(字符流)
            ClassPathResource classPathResource = new ClassPathResource("counter.txt");
            InputStream inputStream = classPathResource.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
            //循环读取数据
            String str = null;
            StringBuffer content = new StringBuffer();
            while ((str = in.readLine()) != null) {
                content.append(str);
            }
            //关闭流
            in.close();
            // 解析获取的数据
            Long count = Long.valueOf(content.toString());

            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0L;
        }
    }
}
